 

import Foundation

public typealias TimerCallBack = (Int) -> Void

open class GlobalTimer: NSObject {
    
    static public let timer = GlobalTimer()
    // 任务缓存
    private var taskCache : [String: TimerCallBack] = [:]
    // 定时器 整个APP进程活跃
    private var timer: Timer!
    // APP活跃时间
    private var lifeTime: Int = 0
    // 是否可调度缓存池任务
    private var taskEnabel: Bool = false
    
    private override init() {
        super.init()
        timer = Timer.init(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
        taskEnabel = true
        RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
    }
    
    @objc private func timerAction() {
        lifeTime += 1
        for key in taskCache.keys {
            if taskEnabel {
                taskCache[key]!(lifeTime)
            } else {
                break
            }
        }
    }
    
    /// 添加任务到缓存池
    /// - Parameters:
    ///   - uniqueIdentifier: 任务唯一标识符 （务必保证id的唯一性，否则会覆盖掉原有的任务回调功能）
    ///   - timerCallBack: 任务回调
    public func add(_ uniqueIdentifier: String, _ timerCallBack: @escaping TimerCallBack) {
        taskEnabel = false
        taskCache[uniqueIdentifier] = timerCallBack
        taskEnabel = true
    }
    
    /// 移除缓存池任务
    /// - Parameter uniqueIdentifier: 任务唯一标识符
    public func remove(_ uniqueIdentifier: String) {
        taskEnabel = false
        taskCache.removeValue(forKey: uniqueIdentifier)
        taskEnabel = true
        print("移除定时任务ID："+uniqueIdentifier)
        
    }
    
}
